import { Routes, Route, useLocation } from 'react-router-dom';
import './App.css';
// App.js 设置了路由链接和注册路由：
import BottomNavBar from './components/BottomNavBar'
import { useEffect, useState, createContext } from 'react';
import FrontendAuth from './utils/FrontendAuth';
import { routerMap } from './utils/routerMap';
import { baseRoutes } from './utils/contants';
import axios from './utils/axios';
import { myContext } from './context';
function App() {
  const [isBaseRoutes, setBaseRoutes] = useState(false)
  // const baseRoutes = ['/', '/category', '/shoppingCart', '/personalCenter'];
  // 1.把 购物车的数量 列表 那个 count 存在 context 里面；
  // 2. 把 userInfo 放到 context 里面
  const [userInfos, setUserInfos] = useState({})
  const [shoppingCartConent, setShoppingCartContent] = useState([])
  const token = JSON.parse(localStorage.getItem('Token')) || ''
  const getUserInfo = () => {
    axios.get('/api/v1/user/info').then(res => {
      if (res.data.message === 'SUCCESS') {
        setUserInfos(res.data.data)
      }
    })
  }

  const getShoppingCartCount = () => {
    axios.get('/api/v1/shop-cart').then(res => {
      if (res.data.message === 'SUCCESS') {
        //如果是 SUCCESS， 就说明 aixos 成功，
        // 应该在 axios里面去设置一个相应拦截？？？？
        setShoppingCartContent(res.data.data)
      }
    })
  }

  useEffect(() => {
    getUserInfo();
    getShoppingCartCount();
  }, [token])


  const pathname = useLocation().pathname;
  useEffect(() => {
    if (baseRoutes.includes(pathname)) {
      setBaseRoutes(true);
    } else {
      setBaseRoutes(false);
    }
  }, [pathname, isBaseRoutes])

  return (
    <div className="App" style={{ paddingBottom: isBaseRoutes ? '4rem' : 0 }}>
      <myContext.Provider value={{
        shoppingCartConent: shoppingCartConent,
        updateShoppingCartConent: setShoppingCartContent,
        userInfos: userInfos,
        updateUserInfo: setUserInfos,
      }}>
        {/* 只有导航地址是 4个主页，才有下面这个导航！ */}
        {
          isBaseRoutes &&
          <BottomNavBar></BottomNavBar>
        }
        <>
          <Routes>
            <Route path={pathname} element={
              <FrontendAuth routerConfig={routerMap} />
            }></Route>
          </Routes>
        </>
      </myContext.Provider>
    </div>
  );
}








export default App;
